﻿using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Web.Mvc;
using Web.Models;
using Web.Models.SearchModels;
using Web.Models.ViewModels;

namespace Web.Areas.ManagerArea.Controllers
{
    public class NewsController : BaseController
    {
        // GET: ManagerArea/News
        public ActionResult Index()
        {
            using(var db = MyDbContext.Create()) ViewBag.CategoryList = db.Categories.Where(m => CategoryIds.News == m.ParentId).ToList();
            return View();
        }

        public ActionResult List(NewsSearchModel searchModel)
        {
            searchModel = searchModel ?? new NewsSearchModel();
            using (var db = MyDbContext.Create())
            {
                IQueryable<News> list = db.News.OrderByDescending(m => m.Id).Include(m => m.Category);
                if (!string.IsNullOrEmpty(searchModel.Title))
                    list = list.Where(m => m.Title.Contains(searchModel.Title));
                if (null != searchModel.CategoryId)
                    list = list.Where(m => m.CategoryId == searchModel.CategoryId);
                list = list.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize);
                var result = new DbDataResult
                {
                    StatusCode = 0,
                    Message = "success",
                    PageSize = searchModel.PageSize,
                    CurrentPage = searchModel.Page,
                    Data = list.Select(m => new
                    {
                        m.Title,
                        m.Id,
                        m.CategoryId,
                        m.Category.CategoryName
                    }).ToList()
                };
                return new LowerCamelJsonResult(result);
            }
        }

        public ActionResult Edit(int? id)
        {
            using (var db = MyDbContext.Create())
            {
                ViewBag.CategoryList = db.Categories.Where(m => CategoryIds.News == m.ParentId).ToList();
                if (null == id) return View();
                var model = db.News.Find(id.Value);
                if (null == model) return HttpNotFound();
                return View(model);
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Edit(News model)
        {
            var result = new DbResult();
            if (ModelState.IsValid)
            {
                using (var db = MyDbContext.Create())
                {
                    db.News.AddOrUpdate(model);
                    db.SaveChanges();
                    result.StatusCode = 0;
                    result.Message = "success";
                }
            }
            else
            {
                AddErrors(out result);
            }
            return new LowerCamelJsonResult(result);
        }
    }
}